﻿using CCWin;
using ERP_SaaS_WinForm.物料管理.Material;
using ERP_SaaS_WinForm.登录.Common;
using ERPWinFormWork;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.物料管理
{
	public partial class MaterialInfoForm : CCSkinMain
	{

        private string _apiClient;
        public MaterialInfoForm()
		{
            _apiClient = AppConfigMaterial.ApiBaseUrl;
            InitializeComponent();
			this.Load += MaterialInfoForm_Load;
			InitializeOutboundGrid();
		}

		private async void MaterialInfoForm_Load(object sender, EventArgs e)
		{
			await QueryAndBindAsync();
			await BindPickingAsync();
        }

		private async void btnSearch_Click(object sender, EventArgs e)
		{
			await QueryAndBindAsync();
		}
	     /// <summary>
		 /// 调用后端接口查询物料信息
		 /// </summary>
		 /// <returns></returns>
		private async Task QueryAndBindAsync()
		{
			string baseUrl = _apiClient + "/api/Material/GetMaterialInfo";
			string materialCode = txtMaterialCode != null ? txtMaterialCode.Text?.Trim() : string.Empty;
			if (!string.IsNullOrEmpty(materialCode))
			{
				baseUrl += $"&MaterialCode={Uri.EscapeDataString(materialCode)}";
			}

			var client = HttpClientProvider.Client;
			try
			{
				HttpResponseMessage response = await client.GetAsync(baseUrl);
				response.EnsureSuccessStatusCode();
				string jsonResponse = await response.Content.ReadAsStringAsync();
				MaterialApiResponse<MaterialInfoDto> apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<MaterialInfoDto>>(jsonResponse);
				if (apiResponse != null && apiResponse.code == 200)
				{
					var list = apiResponse.data;
					dgvMaterialInfo.AutoGenerateColumns = false;
					dgvMaterialInfo.DataSource = list;
				}
				else
				{
					MessageBox.Show($"查询失败{apiResponse?.message}");
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show($"请求失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 初始化领料单列表，添加删除操作列
		/// </summary>
		private void InitializeOutboundGrid()
		{
			if (dgvPinkingInfo == null) return;
			// 只添加一次
			if (!dgvPinkingInfo.Columns.Contains("Delete"))
			{
				var col = new DataGridViewButtonColumn
				{
					Name = "Delete",
					HeaderText = "删除",
					Text = "删除",
					UseColumnTextForButtonValue = true,
					Width = 70
				};
				dgvPinkingInfo.Columns.Add(col);
			}
			// 绑定单击事件
			dgvPinkingInfo.CellClick -= dgvPinkingInfo_CellClick;
			dgvPinkingInfo.CellClick += dgvPinkingInfo_CellClick;
		}

	
		
		/// <summary>
		/// 处理删除按钮点击
		/// </summary>
		private async void dgvPinkingInfo_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0) return;
			if (!dgvPinkingInfo.Columns.Contains("Delete")) return;
			if (e.ColumnIndex != dgvPinkingInfo.Columns["Delete"].Index) return;

			var dto = dgvPinkingInfo.Rows[e.RowIndex].DataBoundItem as PinkingInfoDto;
			if (dto == null) return;
			int id = dto.outboundId;
			if (id <= 0)
			{
				MessageBox.Show("未获取到要删除的记录ID(OutboundId)");
				return;
			}

			if (MessageBox.Show("确定要删除该领料单记录吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				await DeleteOutboundAsync(id);
			}
		}

		/// <summary>
		/// 调用后端删除接口
		/// </summary>
		private async Task DeleteOutboundAsync(int id)
		{
			string url = $"http://10.223.8.23:8008/api/Pinking/DelOutboundRecord?Id={id}";
			var client = HttpClientProvider.Client;
			try
			{
				var resp = await client.GetAsync(url);
				if (resp.IsSuccessStatusCode)
				{
					MessageBox.Show("删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
					await BindPickingAsync();
				}
				else
				{
					string body = await resp.Content.ReadAsStringAsync();
					MessageBox.Show($"删除失败: {resp.StatusCode} {body}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show($"删除发生异常: {ex.Message}");
			}
		}

        private void dgvMaterialInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
			string materialCode = dgvMaterialInfo.Rows[e.RowIndex].Cells["物料编号"].Value.ToString();

        }

        private void btnMaterialInfo_Click(object sender, EventArgs e)
        {

        }
        private async Task BindPickingAsync()
        {
            string baseUrl = "http://10.223.8.23:8008/api/Material/GetOutboundRecord";
            var client = HttpClientProvider.Client;
            try
            {
                HttpResponseMessage response = await client.GetAsync(baseUrl);
                response.EnsureSuccessStatusCode();
                string jsonResponse = await response.Content.ReadAsStringAsync();
                MaterialApiResponse<PinkingInfoDto> apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse<PinkingInfoDto>>(jsonResponse);
                if (apiResponse.code == 200)
                {
                    dgvPinkingInfo.AutoGenerateColumns = false;
                    dgvPinkingInfo.DataSource = apiResponse.data;
                }
                else
                {
                    MessageBox.Show($"查询失败{apiResponse?.message}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"请求失败: {ex.Message}");
            }
        }
    }
}
